package com.suguowen.sblog.config.shiro;

import com.suguowen.sblog.bean.User;
import com.suguowen.sblog.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

public class UserRealm  extends AuthorizingRealm {

    @Autowired
    UserService userService;

    /**
     * 执行授权逻辑
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行授权逻辑");
        // 给资源授权
        SimpleAuthorizationInfo info  =new SimpleAuthorizationInfo();

        // 添加资源授权字符串
        // 若当前用户是当前博客的主人，则给予授权
        // 1.获取当前用户
        Subject subject = SecurityUtils.getSubject();
        User user = (User)subject.getPrincipal();
        // 2. 获取当前博客主人
        User blogUser = userService.findByName("5001");// 写死了，项目只有唯一博客主，其他账户为游客
        if (user.getId().equals(blogUser.getId())){
            info.addStringPermission("user:manager");
        }

        return info;
    }

    /**
     * 执行认证逻辑
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("执行认证逻辑");

        // 假设数据库用户名密码
        /*String name = "admin";
        String password = "123";*/

        // 编写Shiro判断逻辑，判断用户名和密码
        UsernamePasswordToken token = (UsernamePasswordToken)authenticationToken;

        User user = userService.findByName(token.getUsername());

        // 1.判断用户名
        if (user == null){
            return null;// Shiro底层会抛出UnknowAccountException
        }
        // 2.判断密码
        return new SimpleAuthenticationInfo(user,user.getPassword(),"");
    }
}
